﻿(function () {
    "use strict";

    angular.module("codeVerificationSystem")
        .controller("MainCtrl",
        [
            "userAccount",
            "currentUser",
            "$uibModal",
            MainCtrl
        ]);

    function MainCtrl(userAccount, currentUser, $uibModal) {
        var vm = this;

        vm.openRegistrationDialog = function() {
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'app/registration/registrationView.html',
                controller: 'RegistrationCtrl as vm'
            });
            modalInstance.result.then(function () {

            }, function () {

            });
        }

        vm.isLoggedIn = function () {
            return currentUser.getProfile().isLoggedIn;
        };
        vm.message = '';
        vm.getProfile = function() {
            return currentUser.getProfile();
        }

        vm.login = function () {
            vm.userData.grant_type = "password";
            vm.userData.userName = vm.userData.email;

            userAccount.login.loginUser(vm.userData,
                function (data) {
                    vm.message = "";
                    vm.password = "";
                    currentUser.setProfile(vm.userData.userName, JSON.parse(data.roles), data.access_token);
                },
                function (response) {
                    vm.password = "";
                    vm.message = response.statusText + "\r\n";
                    if (response.data.exceptionMessage)
                        vm.message += response.data.exceptionMessage;

                    if (response.data.error) {
                        vm.message += response.data.error;
                    }

                    alert(vm.message);
                });
        };
    }
})();
